package com.mojito.gorm.datasource;

import com.mojito.gorm.session.GormConfiguration;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 获取数据库连接
 *
 * @author mojito
 */
@Slf4j
public class ConnectionManager {
    /**
     * 这里获取数据库连接的当时很简单,后续可以仿照mybatis的数据库连接池整改
     */

    private static final Map<String, String> DRIVER_REGISTRY = new ConcurrentHashMap<>(4);

    public static Connection getConn() {

        if (DRIVER_REGISTRY.isEmpty()) {
            String driverName = GormConfiguration.properties.getString("jdbc.driver");
            try {
                Class.forName(driverName);
                DRIVER_REGISTRY.put(driverName, driverName);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        String username = GormConfiguration.properties.getString("jdbc.username");
        String url = GormConfiguration.properties.getString("jdbc.url");
        String password = GormConfiguration.properties.getString("jdbc.password");
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
        return connection;
    }
}
